package com.wanli.storemobile.homepage;


import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.wanli.storemobile.R;
import com.wanli.storemobile.base.BaseActivity;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.BaseResponseBean;
import com.wanli.storemobile.bean.CreateOrderBean;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.homepage.model.IHomePageModel;
import com.wanli.storemobile.utils.CashierInputFilter;
import com.wanli.storemobile.utils.FastClickUtils;
import com.wanli.storemobile.utils.NumberFormatUtils;
import com.wanli.storemobile.utils.ToastUtil;
import com.wanli.storemobile.widget.AppTitleBar;


import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import androidx.annotation.NonNull;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;
import java.util.Objects;
import android.provider.Settings;

public class ScanCodeActivity extends BaseActivity {

    @BindView(R.id.edit_money)
    EditText editMoney;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    private IHomePageModel homePageModel;
    private String order_no;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private int count;
    private Runnable mTimeCounterRunnable = new Runnable() {
        @Override
        public void run() {
            count++;
            if (count >= 30) {
                ToastUtil.showShort("收款失败");
                dismissProgress();
                mHandler.removeCallbacks(mTimeCounterRunnable);
            } else {
                requestStoreOrderShow();
            }
        }
    };
    private String moneyUnit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_code);
        ButterKnife.bind(this);
        initView();
    }

    public void initView() {
        homePageModel = new HomePageModelImpl();
        InputFilter[] filters = {new CashierInputFilter()};
        editMoney.setFilters(filters);
    }

    @OnClick({R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_commit:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                String money = editMoney.getText().toString();
                if (TextUtils.isEmpty(money)) {
                    ToastUtil.showShort("请输入金额");
                    return;
                }
                if (Double.parseDouble(money) <= 0) {
                    ToastUtil.showShort("金额必须大于0元");
                    return;
                }
                //扫一扫
                scanCode();
                break;
        }
    }


    private int REQUEST_CODE_SCAN = 111;//扫一扫请求状态码

    public void scanCode() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Intent intent = new Intent(ScanCodeActivity.this, CaptureActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + Objects.requireNonNull(ScanCodeActivity.this).getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(ScanCodeActivity.this, "没有权限无法扫描呦", Toast.LENGTH_LONG).show();
                    }
                })
                .start();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
//                Log.e(TAG, "扫码返回: " + content);
                requestStoreOrderAdd(content);
            }
        }
    }


    private void requestStoreOrderAdd(String auth_code) {
        if (!NumberFormatUtils.isNumeric(auth_code)) {
            ToastUtil.showShort("请扫描付款码");
            return;
        }
        String money = editMoney.getText().toString();
        //钱数 单位分
        moneyUnit = String.valueOf(Double.parseDouble(money) * 100);
        moneyUnit = moneyUnit.substring(0, moneyUnit.indexOf("."));
        showProgress("收款中.....");
        homePageModel.requestStoreOrderAdd("1", moneyUnit, auth_code, "", new DataCallBack<CreateOrderBean>() {
            @Override
            public void onSuccessful(CreateOrderBean bean) {
                order_no = bean.getData().getOrder_no();
                requestStoreOrderScanCode(moneyUnit, auth_code);
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    /**
     * 支付订单
     */
    private void requestStoreOrderScanCode(String moneyUnit, String auth_code) {
        homePageModel.requestStoreOrderScanCode("1", moneyUnit, auth_code, "", order_no, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                requestStoreOrderShow();
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    /**
     * 轮询订单
     */
    private void requestStoreOrderShow() {
        homePageModel.requestStoreOrderShow(order_no, new DataCallBack<CreateOrderBean>() {
            @Override
            public void onSuccessful(CreateOrderBean bean) {
                if (bean.getData().getPay_status() == 1) {
                    String money = editMoney.getText().toString();
                    Intent intent = new Intent(mActivity, CashierSuccessActivity.class);
                    intent.putExtra("money", money);
                    startActivity(intent);
                    ToastUtil.showShort("收款成功");
                    dismissProgress();
                    editMoney.setText("");
                    mHandler.removeCallbacks(mTimeCounterRunnable);
                } else if (bean.getData().getPay_status() == 2) {
                    ToastUtil.showShort(bean.getData().getOrder_remark());
                    dismissProgress();
                    mHandler.removeCallbacks(mTimeCounterRunnable);
                } else {
                    mHandler.postDelayed(mTimeCounterRunnable, 1 * 1000);
                }
                Log.d("--------", "" + order_no);
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭定时任务
        mHandler.removeCallbacks(mTimeCounterRunnable);
    }

    private Dialog progress;

    public void showProgress(String message) {
        if (progress == null) {
            progress = new Dialog(mActivity, R.style.ShowProgressUtils);
        }
        View view = View.inflate(mActivity, R.layout.dialog_view_loading, null);
        TextView textView = view.findViewById(R.id.loadingText);
        textView.setText(message);
        progress.setContentView(view);
        progress.setCanceledOnTouchOutside(false);
        progress.setCancelable(true);
        try {
            progress.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissProgress() {
        if (progress == null) {
            return;
        }
        try {
            progress.dismiss();
            progress = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
